<template>
  <div>
    <div class="roleInfo">
      <div class="infoHeader">
        <div class="colorTag"></div>
        <div class="title">Role Info</div>
      </div>
      <div class="infoBody">
        <el-form
          ref="roleFormRef"
          :model="roleForm"
          :rules="roleFormRules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="Role Name" prop="roleName">
            <el-input
              v-model="roleForm.roleName"
              style="width: 26%"
              maxlength="8"
              placeholder="请输入角色名称（8字以内）"
            />
          </el-form-item>
          <el-form-item label="Description" prop="description">
            <el-input
              :autosize="{ minRows: 4, maxRows: 5 }"
              v-model="roleForm.description"
              maxlength="200"
              show-word-limit
              placeholder="请输入角色描述"
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="roleInfo">
      <div class="infoHeader">
        <div class="colorTag"></div>
        <div class="title">Role Info</div>
      </div>
      <div class="infoBody">
        <el-form
          class="rolePermission"
          ref="rolePermissionRef"
          :model="rolePermission"
          :rules="rolePermissionRules"
          label-width="100px"
        >
          <el-form-item label="数据权限：" prop="dataPermission">
            <el-checkbox-group v-model="rolePermission.dataPermission">
              <el-checkbox label="APPS-AUTO" />
              <el-checkbox label="APPS-CPRD MNC" />
              <el-checkbox label="APPS-MLS" />
              <el-checkbox label="APPS-CPRD Local" />
              <el-checkbox label="APPS-OTHERS" />
              <el-checkbox label="INVENT" />
            </el-checkbox-group>
            <!-- <el-radio-group v-model="rolePermission.dataPermission">
              <el-radio label="1">全部数据</el-radio>
              <el-radio label="2">行业线数据</el-radio>
              <el-radio label="3">个人数据</el-radio>
            </el-radio-group> -->
          </el-form-item>
          <el-form-item label="功能权限：" prop="menuBtnPermission">
            <el-tree
              icon-class="none"
              :data="treeData"
              show-checkbox
              node-key="code"
              ref="treeRef"
              :expand-on-click-node="false"
              @check-change="handleCheckChange"
              :default-checked-keys="defaultCheckedCodes"
              :props="{ class: customNodeClass }"
              default-expand-all
            >
            </el-tree>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="bottomBtn">
      <el-button type="primary" color="#3A62D7" @click="saveForm()"
        >Save</el-button
      >
      <el-button @click="handleBack">Cancel</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { current } from '@/api/login'
import { saveRole } from '@/api/role'
import router from '@/router'
import { ElMessage } from 'element-plus'

const roleForm = ref({
  roleName: '',
  description: ''
})
const roleFormRef = ref()

const rolePermission = ref({
  dataPermission: [],
  menuPermission: []
})
const rolePermissionRef = ref()
const treeRef = ref(null)

const roleFormRules = reactive({
  roleName: [
    {
      required: true,
      message: '请输入角色名称',
      trigger: 'blur'
    }
  ],
  description: [
    {
      required: false,
      message: 'Please input your description',
      trigger: 'blur'
    }
  ]
})
const rolePermissionRules = reactive({
  dataPermission: [
    {
      required: true,
      message: '请选择数据权限',
      trigger: 'blur'
    }
  ]
})

const customNodeClass = (data, node) => {
  // console.log(data);
  if (data.isPenultimate === 'rootNode') {
    console.log(data.isPenultimate)
    return 'rootNodeStyle'
  } else if (data.isPenultimate === 'secondNode') {
    return 'secondNoodStyle'
  }
  return null
}

const saveForm = async () => {
  treeData.forEach((item) => {
    if (item.children && item.children.length > 0) {
      item.children.forEach((item1) => {
        if (item1.children && item1.children.length > 0) {
          item1.children.forEach((item2) => {
            rolePermission.value.menuPermission.forEach((item3) => {
              if (item3 === item2.code) {
                // console.log(item1.code)
                if (!rolePermission.value.menuPermission.includes(item1.code)) {
                  rolePermission.value.menuPermission.push(item1.code)
                  console.log('??', rolePermission.value.menuPermission)
                }
              }
            })
          })
        }
      })
    }
  })
  let roleArr = []
  rolePermission.value.menuPermission.forEach((item) => {
    if (!item.includes('Root')) {
      roleArr.push(item)
    }
  })
  console.log(roleArr)
  roleFormRef.value.validate(async (valid) => {
    if (valid) {
      rolePermissionRef.value.validate(async (valid1) => {
        if (valid1) {
          console.log('表单', roleForm.value)
          console.log('权限', rolePermission.value)
          const res = await saveRole({
            description: roleForm.value.description,
            codes: roleArr,
            roleName: roleForm.value.roleName,
            dataNames: rolePermission.value.dataPermission
          })
          if (res.data.code === '0') {
            ElMessage.success('添加成功')
            router.push('/setings/settings-role')
          } else {
            ElMessage.error(res.data.msg)
          }
        }
      })
    }
  })
}

const handleBack = () => {
  router.back()
}
const handleCheckChange = (checkedNodes) => {
  // console.log('1111:---',checkedNodes);
  // console.log(treeRef.value.getCheckedNodes())
  rolePermission.value.menuPermission = treeRef.value.getCheckedKeys()
  console.log(treeRef.value.getCheckedKeys())
}
const defaultCheckedCodes = [
  // 'DashBoard', 'Upload-PT', 'Detail-Report'
]
const treeData = [
  {
    code: 'DashBoard',
    label: 'DashBoard',
    isPenultimate: 'rootNode'
  },
  {
    code: 'PTList-Root',
    label: 'PTList',
    isPenultimate: 'rootNode',
    children: [
      {
        code: 'PTList',
        label: 'List',
        isPenultimate: 'secondNode',
        children: [
          {
            code: 'Upload-PT',
            label: 'Upload'
          },
          // {
          //   code: 'CrabData-PT',
          //   label: 'Crab Data'
          // },
          // {
          //   code: 'Detail-PT',
          //   label: 'Detail'
          // },
          // {
          //   code: 'Update-PT',
          //   label: 'Update'
          // },
          {
            code: 'Detele-PT',
            label: 'Detele'
          }
        ]
      }
    ]
  },
  {
    code: 'Report',
    label: 'Report',
    isPenultimate: 'rootNode'
    // children: [
    //   {
    //     code: 'Report',
    //     label: 'Report',
    //     isPenultimate: 'secondNode',
    //     children: [
    //       {
    //         code: 'Detail-Report',
    //         label: 'Detail'
    //       },
    //       {
    //         code: 'Update-Report',
    //         label: 'Update'
    //       },
    //       {
    //         code: 'Detele-Report',
    //         label: 'Detele'
    //       }
    //     ]
    //   }
    // ]
  },
  {
    code: 'Settings-Root',
    label: 'Settings',
    isPenultimate: 'rootNode',
    children: [
      {
        code: 'Roles-setting',
        label: 'Role Setting',
        isPenultimate: 'secondNode',
        children: [
          {
            code: 'Create-Role',
            label: 'Create'
          },
          {
            code: 'Update-Role',
            label: 'Update'
          },
          {
            code: 'Detele-Role',
            label: 'Detele'
          },
          {
            code: 'Role-Detail',
            label: 'Detail'
          }
        ]
      },
      {
        code: 'Account-Setting',
        label: 'Account Setting',
        isPenultimate: 'secondNode',
        children: [
          {
            code: 'Create-Account',
            label: 'Create'
          },
          {
            code: 'Update-Account',
            label: 'Update'
          },
          {
            code: 'Detele-Account',
            label: 'Detele'
          },
          {
            code: 'Account-Detail',
            label: 'Detail'
          }
        ]
      }
    ]
  }
]
</script>

<style lang="scss" scoped>
.el-form {
  width: 98%;
}
.roleInfo {
  background-color: #edf1fb;
  padding-bottom: 4px;
  border-radius: 20px;
  margin: 10px;

  .infoHeader {
    display: flex;
    justify-content: start;
    padding-top: 34px;
    height: 30px;
    line-height: 30px;
    .colorTag {
      width: 8px;
      border-top-right-radius: 7px;
      border-bottom-right-radius: 7px;
      background-color: #3a62d7;
      margin-right: 16px;
    }
    .title {
      font-weight: 600;
    }
  }
  .infoBody {
    margin: 32px 10px 10px 10px;
  }
}
::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
  position: absolute;
  pointer-events: none;
  opacity: 1;
}
::v-deep .rootNodeStyle > .el-tree-node__content {
  color: #6c6c6c;
  background: #d5def7;
  font-weight: 600;
  width: 134px;
  overflow: hidden;
  border-top-right-radius: 26px;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 26px;
  border-top-left-radius: 5px;
  margin-bottom: 16px;
  padding-left: 22px !important;
}
::v-deep .secondNoodStyle > .el-tree-node__content {
  font-weight: 600;
  width: 130px;
}

::v-deep .el-tree-node__content {
  position: relative;
  height: 36px;
  display: flex;
}

::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: flex;
  margin-left: 40px;
}
::v-deep .el-tree {
  width: 100%;
  padding: 20px 20px 20px 0;
}
::v-deep .el-button {
  width: 76px;
}
.bottomBtn {
  display: flex;
  justify-content: end;
  margin-right: 42px;
  margin-top: 26px;
}
</style>
